home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.006 / xemacs-1 / lib / xemacs-19.13 / lisp / modes / old-c-mode.el < prev    next >
Encoding:
Text File  |  1995-05-12  |  54.3 KB  |  1,420 lines

  1. ;;; c-mode.el --- C code editing commands for Emacs
  2. ;; Copyright (C) 1985, 1986, 1987, 1992, 1994 Free Software Foundation, Inc.
  3.  
  4. ;; Maintainer: FSF
  5. ;; Keywords: c
  6.  
  7. ;; This file is part of XEmacs.
  8.  
  9. ;; XEmacs is free software; you can redistribute it and/or modify it
  10. ;; under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 2, or (at your option)
  12. ;; any later version.
  13.  
  14. ;; XEmacs is distributed in the hope that it will be useful, but
  15. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17. ;; General Public License for more details.
  18.  
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with XEmacs; see the file COPYING.  If not, write to the Free
  21. ;; Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  22.  
  23. ;;; Synched up with: FSF 19.28.
  24.  
  25. ;;; Commentary:
  26.  
  27. ;; A smart editing mode for C code.  It knows a lot about C syntax and tries
  28. ;; to position the curser according to C layout conventions.  You can
  29. ;; change the details of the layout style with option variables.  Load it
  30. ;; and do M-x describe-mode for details.
  31.  
  32. ;;; Code:
  33.  
  34. (defvar c-mode-abbrev-table nil
  35.   "Abbrev table in use in C mode.")
  36. (define-abbrev-table 'c-mode-abbrev-table ())
  37.  
  38. (defvar c-mode-map ()
  39.   "Keymap used in C mode.")
  40. ;; XEmacs change: if cc-mode is loaded, then override its keymap.
  41. ;; otherwise things will be really screwed up.
  42. (if (or (null c-mode-map) (featurep 'cc-mode))
  43.     (progn
  44.       (setq c-mode-map (make-sparse-keymap))
  45.       (set-keymap-name c-mode-map 'c-mode-map)
  46.       (define-key c-mode-map "{" 'electric-c-brace)
  47.       (define-key c-mode-map "}" 'electric-c-brace)
  48.       (define-key c-mode-map ";" 'electric-c-semi)
  49.       (define-key c-mode-map "#" 'electric-c-sharp-sign)
  50.       (define-key c-mode-map ":" 'electric-c-terminator)
  51.       (define-key c-mode-map "\e{" 'c-insert-braces)
  52.       ;; Commented out electric square brackets because nobody likes them.
  53.       ;;(define-key c-mode-map "[" 'c-insert-brackets)
  54.       (define-key c-mode-map "\e\C-h" 'mark-c-function)
  55.       (define-key c-mode-map "\e\C-q" 'indent-c-exp)
  56.       (define-key c-mode-map "\ea" 'c-beginning-of-statement)
  57.       (define-key c-mode-map "\ee" 'c-end-of-statement)
  58.       (define-key c-mode-map "\eq" 'c-fill-paragraph)
  59.       (define-key c-mode-map "\C-c\C-n" 'c-forward-conditional)
  60.       (define-key c-mode-map "\C-c\C-p" 'c-backward-conditional)
  61.       (define-key c-mode-map "\C-c\C-u" 'c-up-conditional)
  62.       (define-key c-mode-map "\177" 'backward-delete-char-untabify)
  63.       (define-key c-mode-map "\t" 'c-indent-command)))
  64.  
  65. ;; cmacexp is lame because it uses no preprocessor symbols.
  66. ;; It isn't very extensible either -- hardcodes /lib/cpp.
  67. (autoload 'c-macro-expand "cmacexp"
  68.   "Display the result of expanding all C macros occurring in the region.
  69. The expansion is entirely correct because it uses the C preprocessor."
  70.   t)
  71.  
  72. (defvar c-mode-syntax-table nil
  73.   "Syntax table in use in C-mode buffers.")
  74.  
  75. (if c-mode-syntax-table
  76.     ()
  77.   (setq c-mode-syntax-table (make-syntax-table))
  78.   (modify-syntax-entry ?\\ "\\" c-mode-syntax-table)
  79.   (modify-syntax-entry ?/ ". 14" c-mode-syntax-table)
  80.   (modify-syntax-entry ?* ". 23" c-mode-syntax-table)
  81.   (modify-syntax-entry ?+ "." c-mode-syntax-table)
  82.   (modify-syntax-entry ?- "." c-mode-syntax-table)
  83.   (modify-syntax-entry ?= "." c-mode-syntax-table)
  84.   (modify-syntax-entry ?% "." c-mode-syntax-table)
  85.   (modify-syntax-entry ?< "." c-mode-syntax-table)
  86.   (modify-syntax-entry ?> "." c-mode-syntax-table)
  87.   (modify-syntax-entry ?& "." c-mode-syntax-table)
  88.   (modify-syntax-entry ?| "." c-mode-syntax-table)
  89.   (modify-syntax-entry ?\' "\"" c-mode-syntax-table))
  90.  
  91. (defvar c-indent-level 2
  92.   "*Indentation of C statements with respect to containing block.")
  93. (defvar c-brace-imaginary-offset 0
  94.   "*Imagined indentation of a C open brace that actually follows a statement.")
  95. (defvar c-brace-offset 0
  96.   "*Extra indentation for braces, compared with other text in same context.")
  97. (defvar c-argdecl-indent 5
  98.   "*Indentation level of declarations of C function arguments.")
  99. (defvar c-label-offset -2
  100.   "*Offset of C label lines and case statements relative to usual indentation.")
  101. (defvar c-continued-statement-offset 2
  102.   "*Extra indent for lines not starting new statements.")
  103. (defvar c-continued-brace-offset 0
  104.   "*Extra indent for substatements that start with open-braces.
  105. This is in addition to c-continued-statement-offset.")
  106.  
  107. (defvar c-auto-newline nil
  108.   "*Non-nil means automatically newline before and after braces,
  109. and after colons and semicolons, inserted in C code.
  110. If you do not want a leading newline before braces then use:
  111.   (define-key c-mode-map \"{\" 'electric-c-semi)")
  112.  
  113. (defvar c-tab-always-indent t
  114.   "*Non-nil means TAB in C mode should always reindent the current line,
  115. regardless of where in the line point is when the TAB command is used.")
  116.  
  117. ;;; Regular expression used internally to recognize labels in switch
  118. ;;; statements.
  119. (defvar c-switch-label-regexp
  120.   (purecopy "case[ \t'/(]\\|default\\(\\S_\\|'\\)"))
  121.  
  122.  
  123. (defun c-mode ()
  124.   "Major mode for editing C code.
  125. Expression and list commands understand all C brackets.
  126. Tab indents for C code.
  127. Comments are delimited with /* ... */.
  128. Paragraphs are separated by blank lines only.
  129. Delete converts tabs to spaces as it moves back.
  130. \\{c-mode-map}
  131. Variables controlling indentation style:
  132.  c-tab-always-indent
  133.     Non-nil means TAB in C mode should always reindent the current line,
  134.     regardless of where in the line point is when the TAB command is used.
  135.  c-auto-newline
  136.     Non-nil means automatically newline before and after braces,
  137.     and after colons and semicolons, inserted in C code.
  138.  c-indent-level
  139.     Indentation of C statements within surrounding block.
  140.     The surrounding block's indentation is the indentation
  141.     of the line on which the open-brace appears.
  142.  c-continued-statement-offset
  143.     Extra indentation given to a substatement, such as the
  144.     then-clause of an if or body of a while.
  145.  c-continued-brace-offset
  146.     Extra indentation given to a brace that starts a substatement.
  147.     This is in addition to c-continued-statement-offset.
  148.  c-brace-offset
  149.     Extra indentation for line if it starts with an open brace.
  150.  c-brace-imaginary-offset
  151.     An open brace following other text is treated as if it were
  152.     this far to the right of the start of its line.
  153.  c-argdecl-indent
  154.     Indentation level of declarations of C function arguments.
  155.  c-label-offset
  156.     Extra indentation for line that is a label, or case or default.
  157.  
  158. Settings for K&R and BSD indentation styles are
  159.   c-indent-level                5    8
  160.   c-continued-statement-offset  5    8
  161.   c-brace-offset               -5   -8
  162.   c-argdecl-indent              0    8
  163.   c-label-offset               -5   -8
  164.  
  165. Turning on C mode calls the value of the variable c-mode-hook with no args,
  166. if that value is non-nil."
  167.   (interactive)
  168.   (kill-all-local-variables)
  169.   (use-local-map c-mode-map)
  170.   (setq major-mode 'c-mode)
  171.   (setq mode-name "C")
  172.   (setq local-abbrev-table c-mode-abbrev-table)
  173.   (set-syntax-table c-mode-syntax-table)
  174.   (make-local-variable 'paragraph-start)
  175.   (setq paragraph-start (concat "^$\\|" page-delimiter))
  176.   (make-local-variable 'paragraph-separate)
  177.   (setq paragraph-separate paragraph-start)
  178.   (make-local-variable 'paragraph-ignore-fill-prefix)
  179.   (setq paragraph-ignore-fill-prefix t)
  180.   (make-local-variable 'indent-line-function)
  181.   (setq indent-line-function 'c-indent-line)
  182.   (make-local-variable 'indent-region-function)
  183.   (setq indent-region-function 'c-indent-region)
  184.   (make-local-variable 'require-final-newline)
  185.   (setq require-final-newline t)
  186.   (make-local-variable 'comment-start)
  187.   (setq comment-start "/* ")
  188.   (make-local-variable 'comment-end)
  189.   (setq comment-end " */")
  190.   (make-local-variable 'comment-column)
  191.   (setq comment-column 32)
  192.   (make-local-variable 'comment-start-skip)
  193.   (setq comment-start-skip "/\\*+ *")
  194.   (make-local-variable 'comment-indent-function)
  195.   (setq comment-indent-function 'c-comment-indent)
  196.   (make-local-variable 'parse-sexp-ignore-comments)
  197.   (setq parse-sexp-ignore-comments t)
  198.   (run-hooks 'c-mode-hook))
  199.  
  200. ;; This is used by indent-for-comment
  201. ;; to decide how much to indent a comment in C code
  202. ;; based on its context.
  203. (defun c-comment-indent ()
  204.   (if (looking-at "^/\\*")
  205.       0                ;Existing comment at bol stays there.
  206.     (let ((opoint (point)))
  207.       (save-excursion
  208.     (beginning-of-line)
  209.     (cond ((looking-at "[ \t]*}[ \t]*\\($\\|/\\*\\)")
  210.            ;; A comment following a solitary close-brace
  211.            ;; should have only one space.
  212.            (search-forward "}")
  213.            (1+ (current-column)))
  214.           ((or (looking-at "^#[ \t]*endif[ \t]*")
  215.            (looking-at "^#[ \t]*else[ \t]*"))
  216.            7)            ;2 spaces after #endif
  217.           ((progn
  218.          (goto-char opoint)
  219.          (skip-chars-backward " \t")
  220.          (and (= comment-column 0) (bolp)))
  221.            ;; If comment-column is 0, and nothing but space
  222.            ;; before the comment, align it at 0 rather than 1.
  223.            0)
  224.           (t
  225.            (max (1+ (current-column))    ;Else indent at comment column
  226.             comment-column)))))))    ; except leave at least one space.
  227.  
  228. (defun c-fill-paragraph (&optional arg)
  229.   "Like \\[fill-paragraph] but handle C comments.
  230. If any of the current line is a comment or within a comment,
  231. fill the comment or the paragraph of it that point is in,
  232. preserving the comment indentation or line-starting decorations."
  233.   (interactive "P")
  234.   (let* ((first-line (save-excursion
  235.                        ;; Check for obvious entry to comment.
  236.                        (beginning-of-line)
  237.                        (skip-chars-forward " \t\n")
  238.                        (and (looking-at comment-start-skip)
  239.                             (point))))
  240.          (comment-start-place first-line))
  241.     (if (or first-line
  242.             ;; t if we enter a comment between start of function and this line.
  243.         (eq (calculate-c-indent) t)
  244.         ;; t if this line contains a comment starter.
  245.         (setq first-line
  246.           (save-excursion
  247.             (beginning-of-line)
  248.             (prog1
  249.             (re-search-forward comment-start-skip
  250.                        (save-excursion (end-of-line)
  251.                                (point))
  252.                        t)
  253.               (setq comment-start-place (point))))))
  254.     ;; Inside a comment: fill one comment paragraph.
  255.     (let ((fill-prefix
  256.            ;; The prefix for each line of this paragraph
  257.            ;; is the appropriate part of the start of this line,
  258.            ;; up to the column at which text should be indented.
  259.            (save-excursion
  260.          (beginning-of-line)
  261.          (if (looking-at "[ \t]*/\\*.*\\*/")
  262.              (progn (re-search-forward comment-start-skip)
  263.                 (make-string (current-column) ?\ ))
  264.            (if first-line (forward-line 1))
  265.  
  266.            (let ((line-width (progn (end-of-line) (current-column))))
  267.              (beginning-of-line)
  268.              (prog1
  269.              (buffer-substring
  270.               (point)
  271.  
  272.               ;; How shall we decide where the end of the
  273.               ;; fill-prefix is?
  274.               ;; calculate-c-indent-within-comment bases its value
  275.               ;; on the indentation of previous lines; if they're
  276.               ;; indented specially, it could return a column
  277.               ;; that's well into the current line's text.  So
  278.               ;; we'll take at most that many space, tab, or *
  279.               ;; characters, and use that as our fill prefix.
  280.               (let ((max-prefix-end
  281.                  (progn
  282.                    (move-to-column
  283.                          (calculate-c-indent-within-comment t)
  284.                          t)
  285.                    (point))))
  286.                 (beginning-of-line)
  287.                 (skip-chars-forward " \t*" max-prefix-end)
  288.                 ;; Don't include part of comment terminator
  289.                 ;; in the fill-prefix.
  290.                 (and (eq (following-char) ?/)
  291.                  (eq (preceding-char) ?*)
  292.                  (backward-char 1))
  293.                 (point)))
  294.  
  295.                ;; If the comment is only one line followed by a blank
  296.                ;; line, calling move-to-column above may have added
  297.                ;; some spaces and tabs to the end of the line; the
  298.                ;; fill-paragraph function will then delete it and the
  299.                ;; newline following it, so we'll lose a blank line
  300.                ;; when we shouldn't.  So delete anything
  301.                ;; move-to-column added to the end of the line.  We
  302.                ;; record the line width instead of the position of the
  303.                ;; old line end because move-to-column might break a
  304.                ;; tab into spaces, and the new characters introduced
  305.                ;; there shouldn't be deleted.
  306.  
  307.                ;; If you can see a better way to do this, please make
  308.                ;; the change.  This seems very messy to me.
  309.                (delete-region (progn (move-to-column line-width)
  310.                          (point))
  311.                       (progn (end-of-line) (point))))))))
  312.           (paragraph-start
  313.            ;; Lines containing just a comment start or just an end
  314.            ;; should not be filled into paragraphs they are next to.
  315.            (concat paragraph-start
  316.                        ;; This:
  317.                ;;   "\\|^[ \t]*/\\*[ \t]*$"
  318.                        ;;   "\\|^[ \t]*\\*/[ \t]*$"
  319.                        ;;   "\\|^[ \t/*]*$"
  320.                        ;; is just this:
  321.                        "\\|^[ \t/*]*$"))
  322.           (paragraph-separate
  323.            (concat paragraph-separate
  324.                ;; This:
  325.                        ;;   "\\|^[ \t]*/\\*[ \t]*$"
  326.                        ;;   "\\|^[ \t]*\\*/[ \t]*$"
  327.                        ;;   "\\|^[ \t/*]*$"
  328.                        ;; is just this:
  329.                        "\\|^[ \t/*]*$"))
  330.               (chars-to-delete 0))
  331.       (save-restriction
  332.         ;; Don't fill the comment together with the code following it.
  333.         ;; So temporarily exclude everything before the comment start,
  334.         ;; and everything after the line where the comment ends.
  335.         ;; If comment-start-place is non-nil, the comment starter is there.
  336.         ;; Otherwise, point is inside the comment.
  337.         (narrow-to-region (save-excursion
  338.                 (if comment-start-place
  339.                     (goto-char comment-start-place)
  340.                                     (search-backward "/*"))
  341.                 ;; Protect text before the comment start 
  342.                 ;; by excluding it.  Add spaces to bring back 
  343.                 ;; proper indentation of that point.
  344.                 (let ((column (current-column)))
  345.                   (prog1 (point)
  346.                     (setq chars-to-delete column)
  347.                     (insert-char ?\  column))))
  348.                   (save-excursion
  349.                 (if comment-start-place
  350.                     (goto-char (+ comment-start-place 2)))
  351.                                 (search-forward "*/" nil 'move)
  352.                           (forward-line 1)
  353.                           (point)))
  354.         (fill-paragraph arg)
  355.         (save-excursion
  356.           ;; Delete the chars we inserted to avoid clobbering
  357.           ;; the stuff before the comment start.
  358.           (goto-char (point-min))
  359.           (if (> chars-to-delete 0)
  360.           (delete-region (point) (+ (point) chars-to-delete)))
  361.           ;; Find the comment ender (should be on last line of buffer,
  362.           ;; given the narrowing) and don't leave it on its own line.
  363.           (goto-char (point-max))
  364.           (forward-line -1)
  365.           (search-forward "*/" nil 'move)
  366.           (beginning-of-line)
  367.           (if (looking-at "[ \t]*\\*/")
  368.           (delete-indentation)))))
  369.       ;; Outside of comments: do ordinary filling.
  370.       (fill-paragraph arg))))
  371.  
  372. (defun electric-c-brace (arg)
  373.   "Insert character and correct line's indentation."
  374.   (interactive "P")
  375.   (let ((insertpos nil))
  376.     (if (and (not arg)
  377.          (eolp)
  378.          (or (save-excursion
  379.            (skip-chars-backward " \t")
  380.            (bolp))
  381.          (if c-auto-newline (progn (c-indent-line) (newline) t) nil)))
  382.     (progn
  383.       (insert last-command-char)
  384.       (c-indent-line)
  385.       (if c-auto-newline
  386.           (progn
  387.         (newline)
  388.         ;; (newline) may have done auto-fill
  389.         (setq insertpos (- (point) 2))
  390.         (c-indent-line)))
  391.       (save-excursion
  392.         (if insertpos (goto-char (1+ insertpos)))
  393.         (delete-char -1))))
  394.     (if insertpos
  395.     (save-excursion
  396.       (goto-char insertpos)
  397.       (self-insert-command (prefix-numeric-value arg)))
  398.         (self-insert-command (prefix-numeric-value arg)))))
  399.  
  400. (defun c-insert-brackets ()
  401.   (interactive)
  402.   (insert ?[)
  403.   (save-excursion
  404.     (insert ?])))
  405.  
  406. (defun c-insert-braces ()
  407.   (interactive)
  408.   (setq last-command-char ?{)
  409.   (electric-c-brace 1)
  410.   (newline)
  411.   (c-indent-line)
  412.   (save-excursion
  413.     (newline)
  414.     (insert ?})
  415.     (c-indent-line)))
  416.  
  417. (defun electric-c-sharp-sign (arg)
  418.   "Insert character and correct line's indentation."
  419.   (interactive "P")
  420.   (if (save-excursion
  421.     (skip-chars-backward " \t")
  422.     (bolp))
  423.       (let ((c-auto-newline nil))
  424.     (electric-c-terminator arg))
  425.     (self-insert-command (prefix-numeric-value arg))))
  426.  
  427. (defun electric-c-semi (arg)
  428.   "Insert character and correct line's indentation."
  429.   (interactive "P")
  430.   (if c-auto-newline
  431.       (electric-c-terminator arg)
  432.     (self-insert-command (prefix-numeric-value arg))))
  433.  
  434. (defun electric-c-terminator (arg)
  435.   "Insert character and correct line's indentation."
  436.   (interactive "P")
  437.   (let (insertpos (end (point)))
  438.     (if (and (not arg) (eolp)
  439.          (not (save-excursion
  440.             (beginning-of-line)
  441.             (skip-chars-forward " \t")
  442.             (or (= (following-char) ?#)
  443.             ;; Colon is special only after a label, or case ....
  444.             ;; So quickly rule out most other uses of colon
  445.             ;; and do no indentation for them.
  446.             (and (eq last-command-char ?:)
  447.                  (not (looking-at c-switch-label-regexp))
  448.                  (save-excursion
  449.                    (skip-chars-forward "a-zA-Z0-9_$")
  450.                    (skip-chars-forward " \t")
  451.                    (< (point) end)))
  452.             (progn
  453.               (beginning-of-defun)
  454.               (let ((pps (parse-partial-sexp (point) end)))
  455.                 (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
  456.     (progn
  457.       (insert last-command-char)
  458.       (c-indent-line)
  459.       (and c-auto-newline
  460.            (not (c-inside-parens-p))
  461.            (progn
  462.          (newline)
  463.          ;; (newline) may have done auto-fill
  464.          (setq insertpos (- (point) 2))
  465.          (c-indent-line)))
  466.       (save-excursion
  467.         (if insertpos (goto-char (1+ insertpos)))
  468.         (delete-char -1))))
  469.     (if insertpos
  470.     (save-excursion
  471.       (goto-char insertpos)
  472.       (self-insert-command (prefix-numeric-value arg)))
  473.       (self-insert-command (prefix-numeric-value arg)))))
  474.  
  475. (defun c-inside-parens-p ()
  476.   (condition-case ()
  477.       (save-excursion
  478.     (save-restriction
  479.       (narrow-to-region (point)
  480.                 (progn (beginning-of-defun) (point)))
  481.       (goto-char (point-max))
  482.       (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
  483.     (error nil)))
  484.  
  485. (defun c-indent-command (&optional whole-exp)
  486.   "Indent current line as C code, or in some cases insert a tab character.
  487. If `c-tab-always-indent' is non-nil (the default), always indent current line.
  488. Otherwise, indent the current line only if point is at the left margin
  489. or in the line's indentation; otherwise insert a tab.
  490.  
  491. A numeric argument, regardless of its value,
  492. means indent rigidly all the lines of the expression starting after point
  493. so that this line becomes properly indented.
  494. The relative indentation among the lines of the expression are preserved."
  495.   (interactive "P")
  496.   (if whole-exp
  497.       ;; If arg, always indent this line as C
  498.       ;; and shift remaining lines of expression the same amount.
  499.       (let ((shift-amt (c-indent-line))
  500.         beg end)
  501.     (save-excursion
  502.       (if c-tab-always-indent
  503.           (beginning-of-line))
  504.       ;; Find beginning of following line.
  505.       (save-excursion
  506.         (forward-line 1) (setq beg (point)))
  507.       ;; Find first beginning-of-sexp for sexp extending past this line.
  508.       (while (< (point) beg)
  509.         (forward-sexp 1)
  510.         (setq end (point))
  511.         (skip-chars-forward " \t\n")))
  512.     (if (> end beg)
  513.         (indent-code-rigidly beg end shift-amt "#")))
  514.     (if (and (not c-tab-always-indent)
  515.          (save-excursion
  516.            (skip-chars-backward " \t")
  517.            (not (bolp))))
  518.     (insert-tab)
  519.       (c-indent-line))))
  520.  
  521. (defun c-indent-line ()
  522.   "Indent current line as C code.
  523. Return the amount the indentation changed by."
  524.   (let ((indent (calculate-c-indent nil))
  525.     beg shift-amt
  526.     (case-fold-search nil)
  527.     (pos (- (point-max) (point))))
  528.     (beginning-of-line)
  529.     (setq beg (point))
  530.     (cond ((eq indent nil)
  531.        (setq indent (current-indentation)))
  532.       ((eq indent t)
  533.        (setq indent (calculate-c-indent-within-comment)))
  534.       ((looking-at "[ \t]*#")
  535.        (setq indent 0))
  536.       (t
  537.        (skip-chars-forward " \t")
  538.        (if (listp indent) (setq indent (car indent)))
  539.        (cond ((or (looking-at c-switch-label-regexp)
  540.               (and (looking-at "[A-Za-z]")
  541.                (save-excursion
  542.                  (forward-sexp 1)
  543.                  (looking-at ":"))))
  544.           (setq indent (max 1 (+ indent c-label-offset))))
  545.          ((and (looking-at "else\\b")
  546.                (not (looking-at "else\\s_")))
  547.           (setq indent (save-excursion
  548.                  (c-backward-to-start-of-if)
  549.                  (current-indentation))))
  550.          ((looking-at "}[ \t]*else")
  551.           (setq indent (save-excursion
  552.                  (forward-char)
  553.                  (backward-sexp)
  554.                  (c-backward-to-start-of-if)
  555.                  (current-indentation))))
  556.          ((and (looking-at "while\\b")
  557.                (save-excursion
  558.              (c-backward-to-start-of-do)))
  559.           ;; This is a `while' that ends a do-while.
  560.           (setq indent (save-excursion
  561.                  (c-backward-to-start-of-do)
  562.                  (current-indentation))))
  563.          ((= (following-char) ?})
  564.           (setq indent (- indent c-indent-level)))
  565.          ((= (following-char) ?{)
  566.           (setq indent (+ indent c-brace-offset))))))
  567.     (skip-chars-forward " \t")
  568.     (setq shift-amt (- indent (current-column)))
  569.     (if (zerop shift-amt)
  570.     (if (> (- (point-max) pos) (point))
  571.         (goto-char (- (point-max) pos)))
  572.       (delete-region beg (point))
  573.       (indent-to indent)
  574.       ;; If initial point was within line's indentation,
  575.       ;; position after the indentation.  Else stay at same point in text.
  576.       (if (> (- (point-max) pos) (point))
  577.       (goto-char (- (point-max) pos))))
  578.     shift-amt))
  579.  
  580. (defun calculate-c-indent (&optional parse-start)
  581.   "Return appropriate indentation for current line as C code.
  582. In usual case returns an integer: the column to indent to.
  583. Returns nil if line starts inside a string, t if in a comment."
  584.   (save-excursion
  585.     (beginning-of-line)
  586.     (let ((indent-point (point))
  587.       (case-fold-search nil)
  588.       state
  589.       containing-sexp)
  590.       (if parse-start
  591.       (goto-char parse-start)
  592.     (beginning-of-defun))
  593.       (while (< (point) indent-point)
  594.     (setq parse-start (point))
  595.     (setq state (parse-partial-sexp (point) indent-point 0))
  596.     (setq containing-sexp (car (cdr state))))
  597.       (goto-char indent-point)
  598.       (cond ((or (nth 3 state) (nth 4 state))
  599.          ;; return nil or t if should not change this line
  600.          (nth 4 state))
  601.         ((and (null containing-sexp)
  602.                   (looking-at "[ \t]*{"))
  603.              ;; It starts a function body
  604.              0)
  605.         ((null containing-sexp)
  606.          ;; Line is at top level.  May be data or function definition,
  607.          ;; or may be function argument declaration.
  608.          ;; Indent like the previous top level line
  609.          ;; unless that ends in a closeparen without semicolon,
  610.          ;; in which case this line is the first argument decl.
  611.              (c-backward-to-noncomment (or parse-start (point-min)))
  612.              ;; Look at previous line that's at column 0
  613.              ;; to determine whether we are in top-level decls
  614.              ;; or function's arg decls.  Set basic-indent accordingly.
  615.              (+ (save-excursion
  616.             (re-search-backward "^[^ \^L\t\n#]" nil 'move)
  617.                   (cond ((save-excursion
  618.                            ;; Recognize the DEFUN macro in Emacs...
  619.                            ;; Move down to the (putative) argnames line.
  620.                            (while (and (not (eobp))
  621.                                        (not (looking-at " *[({}#/]")))
  622.                              (forward-line 1))
  623.                            ;; Go back to the DEFUN, if it is one.
  624.                            (condition-case nil
  625.                                (backward-sexp 1)
  626.                              (error))
  627.                            (beginning-of-line)
  628.                            (looking-at "DEFUN\\b"))
  629.                          c-argdecl-indent)
  630.                         ((and (looking-at "\\sw\\|\\s_")
  631.                               ;; This is careful to stop at the first
  632.                               ;; paren if we have
  633.                               ;; int foo Proto ((int, int));
  634.                               (looking-at "[^\"\n=(]*(")
  635.                               (let ((lim (1- (match-end 0))))
  636.                                 (goto-char lim)
  637.                                 (condition-case nil
  638.                    (forward-sexp 1)
  639.                                   (error))
  640.                                 (skip-chars-forward " \t\f")
  641.                    (and (< (point) indent-point)
  642.                     (not (memq (following-char)
  643.                                                 '(?\, ?\;))))
  644.                                 ;; Make sure the "function decl" we found
  645.                                 ;; is not inside a comment.
  646.                                 (let ((comment nil))
  647.                   ;; Move back to the `(' starting arglist
  648.                   ;; -- cthomp
  649.                   (goto-char lim)
  650.                                   (beginning-of-line)
  651.                                   (while (and (not comment)
  652.                                               (search-forward "/*" lim t))
  653.                                     (setq comment
  654.                                           (not (search-forward "*/" lim t))))
  655.                                   (not comment))))
  656.                          c-argdecl-indent)
  657.                         (t
  658.                          0)))
  659.                 ;; Now add a little if this is a continuation line.
  660.                 ;; (if (or (bobp)
  661.                 ;;        (memq (preceding-char) '(?\) ?\; ?\}))
  662.                 ;;        ;; Line with zero indentation
  663.                 ;;        ;; is probably the return-type
  664.                 ;;        ;; of a function definition,
  665.                 ;;        ;; so following line is function name.
  666.                 ;;        (= (current-indentation) 0))
  667.                 ;;    0
  668.                 ;;    c-continued-statement-offset)
  669.                 ))
  670.         ((/= (char-after containing-sexp) ?{)
  671.          ;; line is expression, not statement:
  672.          ;; indent to just after the surrounding open.
  673.          (goto-char (1+ containing-sexp))
  674.          (current-column))
  675.         (t
  676.          ;; Statement level.  Is it a continuation or a new statement?
  677.          ;; Find previous non-comment character.
  678.          (c-backward-to-noncomment containing-sexp)
  679.          ;; Back up over label lines, since they don't
  680.          ;; affect whether our line is a continuation.
  681.          (while (or (eq (preceding-char) ?\,)
  682.             (and (eq (preceding-char) ?:)
  683.                  (or (eq (char-after (- (point) 2)) ?\')
  684.                  (memq (char-syntax (char-after (- (point) 2)))
  685.                        '(?w ?_)))))
  686.            (if (eq (preceding-char) ?\,)
  687.            (progn (forward-char -1)
  688.               (c-backward-to-start-of-continued-exp containing-sexp)))
  689.            (beginning-of-line)
  690.            (c-backward-to-noncomment containing-sexp))
  691.          ;; Check for a preprocessor statement or its continuation lines.
  692.          ;; Move back to end of previous non-preprocessor line.
  693.          (let ((found (point)) stop)
  694.            (while (not stop)
  695.          (cond ((save-excursion (end-of-line 0)
  696.                     (= (preceding-char) ?\\))
  697.             (end-of-line 0))
  698.                ;; This line is not preceded by a backslash.
  699.                ;; So either it starts a preprocessor command
  700.                ;; or any following continuation lines
  701.                ;; should not be skipped.
  702.                ((progn (beginning-of-line) (= (following-char) ?#))
  703.             (end-of-line 0)
  704.             (setq found (point)))
  705.                (t (setq stop t))))
  706.            (goto-char found))
  707.          ;; Now we get the answer.
  708.          (if (and (not (memq (preceding-char) '(nil ?\, ?\; ?\} ?\{)))
  709.               ;; But don't treat a line with a close-brace
  710.               ;; as a continuation.  It is probably the
  711.               ;; end of an enum type declaration.
  712.               (save-excursion
  713.             (goto-char indent-point)
  714.             (skip-chars-forward " \t")
  715.             (not (= (following-char) ?}))))
  716.          ;; This line is continuation of preceding line's statement;
  717.          ;; indent  c-continued-statement-offset  more than the
  718.          ;; previous line of the statement.
  719.          (progn
  720.            (c-backward-to-start-of-continued-exp containing-sexp)
  721.            (+ c-continued-statement-offset (current-column)
  722.               (if (save-excursion (goto-char indent-point)
  723.                       (skip-chars-forward " \t")
  724.                       (eq (following-char) ?{))
  725.               c-continued-brace-offset 0)))
  726.            ;; This line starts a new statement.
  727.            ;; Position following last unclosed open.
  728.            (goto-char containing-sexp)
  729.            ;; Is line first statement after an open-brace?
  730.            (or
  731.          ;; If no, find that first statement and indent like it.
  732.          (save-excursion
  733.            (forward-char 1)
  734.            (let ((colon-line-end 0))
  735.              (while (progn (skip-chars-forward " \t\n")
  736.                    (looking-at "#\\|/\\*\\|case[ \t\n'/(].*:\\|[a-zA-Z0-9_$]*:"))
  737.                ;; Skip over comments and labels following openbrace.
  738.                (cond ((= (following-char) ?\#)
  739.                   (forward-line 1))
  740.                  ((= (following-char) ?\/)
  741.                   (forward-char 2)
  742.                   (search-forward "*/" nil 'move))
  743.                  ;; case or label:
  744.                  (t
  745.                   (save-excursion (end-of-line)
  746.                           (setq colon-line-end (point)))
  747.                   (search-forward ":"))))
  748.              ;; The first following code counts
  749.              ;; if it is before the line we want to indent.
  750.              (and (< (point) indent-point)
  751.               (- (if (> colon-line-end (point))
  752.                   (- (current-indentation) c-label-offset)
  753.                                  (current-column))
  754.                              ;; If prev stmt starts with open-brace, that
  755.                              ;; open brace was offset by c-brace-offset.
  756.                              ;; Compensate to get the column where
  757.                              ;; an ordinary statement would start.
  758.                              (if (= (following-char) ?\{)
  759.                                  c-brace-offset 
  760.                                  0)))))
  761.          ;; If no previous statement,
  762.          ;; indent it relative to line brace is on.
  763.          ;; For open brace in column zero, don't let statement
  764.          ;; start there too.  If c-indent-level is zero,
  765.          ;; use c-brace-offset + c-continued-statement-offset instead.
  766.          ;; For open-braces not the first thing in a line,
  767.          ;; add in c-brace-imaginary-offset.
  768.          (+ (if (and (bolp) (zerop c-indent-level))
  769.             (+ c-brace-offset c-continued-statement-offset)
  770.               c-indent-level)
  771.             ;; Move back over whitespace before the openbrace.
  772.             ;; If openbrace is not first nonwhite thing on the line,
  773.             ;; add the c-brace-imaginary-offset.
  774.             (progn (skip-chars-backward " \t")
  775.                (if (bolp) 0 c-brace-imaginary-offset))
  776.             ;; If the openbrace is preceded by a parenthesized exp,
  777.             ;; move to the beginning of that;
  778.             ;; possibly a different line
  779.             (progn
  780.               (if (eq (preceding-char) ?\))
  781.               (forward-sexp -1))
  782.               ;; Get initial indentation of the line we are on.
  783.               (current-indentation))))))))))
  784.  
  785. (defun calculate-c-indent-within-comment (&optional after-star)
  786.   "Return the indentation amount for line inside a block comment.
  787. Optional arg AFTER-STAR means, if lines in the comment have a leading star,
  788. return the indentation of the text that would follow this star."
  789.   (let (end star-start)
  790.     (save-excursion
  791.       (beginning-of-line)
  792.       (skip-chars-forward " \t")
  793.       (setq star-start (= (following-char) ?\*))
  794.       (skip-chars-backward " \t\n")
  795.       (setq end (point))
  796.       (beginning-of-line)
  797.       (skip-chars-forward " \t")
  798.       (if after-star
  799.       (and (looking-at "\\*")
  800.            (re-search-forward "\\*[ \t]*")))
  801.       (and (re-search-forward "/\\*[ \t]*" end t)
  802.        star-start
  803.        (not after-star)
  804.        (goto-char (1+ (match-beginning 0))))
  805.       (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\*))
  806.       (1+ (current-column))
  807.     (current-column)))))
  808.  
  809.  
  810. (defun c-backward-to-noncomment (lim)
  811.   (let (opoint stop)
  812.     (while (not stop)
  813.       (skip-chars-backward " \t\n\f" lim)
  814.       (setq opoint (point))
  815.       (if (and (>= (point) (+ 2 lim))
  816.            (save-excursion
  817.          (forward-char -2)
  818.          (looking-at "\\*/")))
  819.       (search-backward "/*" lim 'move)
  820.     (setq stop (or (<= (point) lim)
  821.                (save-excursion
  822.              (while (progn
  823.                   (beginning-of-line)
  824.                   (eq ?\\ (char-after (- (point) 2))))
  825.                (forward-char -1)
  826.                (beginning-of-line))
  827.              (skip-chars-forward " \t")
  828.              (not (looking-at "#")))))
  829.     (or stop (beginning-of-line))))))
  830.  
  831. (defun c-backward-to-start-of-continued-exp (lim)
  832.   (if (memq (preceding-char) '(?\) ?\"))
  833.       (forward-sexp -1))
  834.   (beginning-of-line)
  835.   (if (<= (point) lim)
  836.       (goto-char (1+ lim)))
  837.   (skip-chars-forward " \t"))
  838.  
  839. (defun c-backward-to-start-of-if (&optional limit)
  840.   "Move to the start of the last \"unbalanced\" `if'."
  841.   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
  842.   (let ((if-level 1)
  843.     (case-fold-search nil))
  844.     (while (and (not (bobp)) (not (zerop if-level)))
  845.       (backward-sexp 1)
  846.       (cond ((looking-at "else\\b")
  847.          (setq if-level (1+ if-level)))
  848.         ((looking-at "if\\b")
  849.          (setq if-level (1- if-level)))
  850.         ((< (point) limit)
  851.          (setq if-level 0)
  852.          (goto-char limit))))))
  853.  
  854. (defun c-backward-to-start-of-do (&optional limit)
  855.   "If point follows a `do' statement, move to beginning of it and return t.
  856. Otherwise return nil and don't move point."
  857.   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
  858.   (let ((first t)
  859.     (startpos (point))
  860.     (done nil))
  861.     (while (not done)
  862.       (let ((next-start (point)))
  863.     (condition-case nil
  864.         ;; Move back one token or one brace or paren group.
  865.         (backward-sexp 1)
  866.       ;; If we find an open-brace, we lose.
  867.       (error (setq done 'fail)))
  868.     (if done
  869.         nil
  870.       ;; If we reached a `do', we win.
  871.       (if (looking-at "do\\b")
  872.           (setq done 'succeed)
  873.         ;; Otherwise, if we skipped a semicolon, we lose.
  874.         ;; (Exception: we can skip one semicolon before getting
  875.         ;; to a the last token of the statement, unless that token
  876.         ;; is a close brace.)
  877.         (if (save-excursion
  878.           (forward-sexp 1)
  879.           (or (and (not first) (= (preceding-char) ?}))
  880.               (search-forward ";" next-start t
  881.                       (if (and first
  882.                            (/= (preceding-char) ?}))
  883.                       2 1))))
  884.         (setq done 'fail)
  885.           (setq first nil)
  886.           ;; If we go too far back in the buffer, we lose.
  887.           (if (< (point) limit)
  888.           (setq done 'fail)))))))
  889.     (if (eq done 'succeed)
  890.     t
  891.       (goto-char startpos)
  892.       nil)))
  893.  
  894. (defun c-beginning-of-statement (count)
  895.   "Go to the beginning of the innermost C statement.
  896. With prefix arg, go back N - 1 statements.  If already at the beginning of a
  897. statement then go to the beginning of the preceding one.
  898. If within a string or comment, or next to a comment (only whitespace between),
  899. move by sentences instead of statements."
  900.   (interactive "p")
  901.   (let ((here (point)) state)
  902.     (save-excursion
  903.       (beginning-of-defun)
  904.       (setq state (parse-partial-sexp (point) here nil nil)))
  905.     (if (or (nth 3 state) (nth 4 state)
  906.         (looking-at (concat "[ \t]*" comment-start-skip))
  907.         (save-excursion (skip-chars-backward " \t")
  908.                 (goto-char (- (point) 2))
  909.                 (looking-at "\\*/")))
  910.     (forward-sentence (- count))
  911.       (while (> count 0)
  912.     (c-beginning-of-statement-1)
  913.     (setq count (1- count)))
  914.       (while (< count 0)
  915.     (c-end-of-statement-1)
  916.     (setq count (1+ count))))))
  917.  
  918. (defun c-end-of-statement (count)
  919.   "Go to the end of the innermost C statement.
  920. With prefix arg, go forward N - 1 statements.
  921. Move forward to end of the next statement if already at end.
  922. If within a string or comment, move by sentences instead of statements."
  923.   (interactive "p")
  924.   (c-beginning-of-statement (- count)))
  925.  
  926. (defun c-beginning-of-statement-1 ()
  927.   (let ((last-begin (point))
  928.     (first t))
  929.     (condition-case ()
  930.     (progn
  931.       (while (and (not (bobp))
  932.               (progn
  933.             (backward-sexp 1)
  934.             (or first
  935.                 (not (re-search-forward "[;{}]" last-begin t)))))
  936.         (setq last-begin (point) first nil))
  937.       (goto-char last-begin))
  938.       (error (if first (backward-up-list 1) (goto-char last-begin))))))
  939.  
  940. (defun c-end-of-statement-1 ()
  941.   (condition-case ()
  942.       (progn
  943.     (while (and (not (eobp))
  944.             (let ((beg (point)))
  945.               (forward-sexp 1)
  946.               (let ((end (point)))
  947.             (save-excursion
  948.               (goto-char beg)
  949.               (not (re-search-forward "[;{}]" end t)))))))
  950.     (re-search-backward "[;}]")
  951.     (forward-char 1))
  952.     (error 
  953.      (let ((beg (point)))
  954.        (backward-up-list -1)
  955.        (let ((end (point)))
  956.      (goto-char beg)
  957.      (search-forward ";" end 'move))))))
  958.  
  959. (defun mark-c-function ()
  960.   "Put mark at end of C function, point at beginning."
  961.   (interactive)
  962.   (push-mark (point))
  963.   (end-of-defun)
  964.   (push-mark (point) nil t)
  965.   (beginning-of-defun)
  966.   (backward-paragraph))
  967.  
  968. ;; Idea of ENDPOS is, indent each line, stopping when
  969. ;; ENDPOS is encountered.  But it's too much of a pain to make that work.
  970. (defun indent-c-exp (&optional endpos)
  971.   "Indent each line of the C grouping following point."
  972.   (interactive)
  973.   (let* ((indent-stack (list nil))
  974.      (opoint (point))  ;; May be altered below.
  975.      (contain-stack
  976.       (list (if endpos
  977.             (let (funbeg)
  978.               ;; Find previous fcn-start.
  979.               (save-excursion (forward-char 1)
  980.                       (beginning-of-defun)
  981.                       (setq funbeg (point)))
  982.                       (setq opoint funbeg)
  983.               ;; Try to find containing open,
  984.               ;; but don't scan past that fcn-start.
  985.               (save-restriction
  986.             (narrow-to-region funbeg (point))
  987.             (condition-case nil
  988.                 (save-excursion
  989.                   (backward-up-list 1) (point))
  990.               ;; We gave up: must be between fcns.
  991.               ;; Set opoint to beg of prev fcn
  992.               ;; since otherwise calculate-c-indent
  993.               ;; will get wrong answers.
  994.               (error
  995. ;;;#### Commented-out in XEmacs, present in FSFmacs
  996. ;                          (setq opoint funbeg)
  997.                            (point)))))
  998.           (point))))
  999.      (case-fold-search nil)
  1000.      restart outer-loop-done inner-loop-done state ostate
  1001.      this-indent last-sexp
  1002.      at-else at-brace at-while
  1003.      last-depth this-point
  1004.      (next-depth 0))
  1005.     ;; If the braces don't match, get an error right away.
  1006.     (save-excursion
  1007.       (forward-sexp 1))
  1008.     ;; Realign the comment on the first line, even though we don't reindent it.
  1009.     (save-excursion
  1010.       (let ((beg (point)))
  1011.     (and (re-search-forward
  1012.           comment-start-skip
  1013.           (save-excursion (end-of-line) (point)) t)
  1014.              ;; Make sure this isn't a comment alone on a line
  1015.              ;; (which should be indented like code instead).
  1016.              (save-excursion
  1017.                (goto-char (match-beginning 0))
  1018.                (skip-chars-backward " \t")
  1019.                (not (bolp)))
  1020.          ;; Make sure the comment starter we found
  1021.          ;; is not actually in a string or quoted.
  1022.          (let ((new-state
  1023.             (parse-partial-sexp beg (point)
  1024.                     nil nil state)))
  1025.            (and (not (nth 3 new-state)) (not (nth 5 new-state))))
  1026.         (progn (indent-for-comment) (beginning-of-line)))))
  1027.     (save-excursion
  1028.       (setq outer-loop-done nil)
  1029.       (while (and (not (eobp))
  1030.           (if endpos
  1031.                       (< (point) endpos)
  1032.             (not outer-loop-done)))
  1033.     (setq last-depth next-depth)
  1034.     ;; Compute how depth changes over this line
  1035.     ;; plus enough other lines to get to one that
  1036.     ;; does not end inside a comment or string.
  1037.     ;; Meanwhile, do appropriate indentation on comment lines.
  1038.     (setq inner-loop-done nil)
  1039.     (while (and (not inner-loop-done)
  1040.             (not (and (eobp) (setq outer-loop-done t))))
  1041.       (setq ostate state)
  1042.       (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
  1043.                       nil nil state))
  1044.       (setq next-depth (car state))
  1045.       (if (and (car (cdr (cdr state)))
  1046.            (>= (car (cdr (cdr state))) 0))
  1047.           (setq last-sexp (car (cdr (cdr state)))))
  1048.           ;; If this line started within a comment, indent it as such.
  1049.       (if (or (nth 4 ostate) (nth 7 ostate))
  1050.           (c-indent-line))
  1051.           ;; If it ends outside of comments or strings, exit the inner loop.
  1052.           ;; Otherwise move on to next line.
  1053.       (if (or (nth 3 state) (nth 4 state) (nth 7 state))
  1054.           (forward-line 1)
  1055.         (setq inner-loop-done t)))
  1056.     (and endpos
  1057.          (while (< next-depth 0)
  1058.            (setq indent-stack (append indent-stack (list nil)))
  1059.            (setq contain-stack (append contain-stack (list nil)))
  1060.            (setq next-depth (1+ next-depth))
  1061.            (setq last-depth (1+ last-depth))
  1062.            (setcar (nthcdr 6 state) (1+ (nth 6 state)))))
  1063.     (setq outer-loop-done (and (not endpos) (<= next-depth 0)))
  1064.     (if outer-loop-done
  1065.         nil
  1066.       ;; If this line had ..))) (((.. in it, pop out of the levels
  1067.       ;; that ended anywhere in this line, even if the final depth
  1068.       ;; doesn't indicate that they ended.
  1069.       (while (> last-depth (nth 6 state))
  1070.         (setq indent-stack (cdr indent-stack)
  1071.           contain-stack (cdr contain-stack)
  1072.           last-depth (1- last-depth)))
  1073.       (if (/= last-depth next-depth)
  1074.           (setq last-sexp nil))
  1075.       ;; Add levels for any parens that were started in this line.
  1076.       (while (< last-depth next-depth)
  1077.         (setq indent-stack (cons nil indent-stack)
  1078.           contain-stack (cons nil contain-stack)
  1079.           last-depth (1+ last-depth)))
  1080.       (if (null (car contain-stack))
  1081.           (setcar contain-stack (or (car (cdr state))
  1082.                     (save-excursion (forward-sexp -1)
  1083.                             (point)))))
  1084.       (forward-line 1)
  1085.         (skip-chars-forward " \t")
  1086.           ;; Don't really reindent if the line is just whitespace,
  1087.           ;; or if it is past the endpos.
  1088.           ;; (The exit test in the outer while
  1089.           ;; does not exit until we have passed the first line
  1090.           ;; past the region.)
  1091.       (if (or (eolp) (and endpos (>= (point) endpos)))
  1092.         nil
  1093.             (progn
  1094.           (if (and (car indent-stack)
  1095.                (>= (car indent-stack) 0))
  1096.           ;; Line is on an existing nesting level.
  1097.           ;; Lines inside parens are handled specially.
  1098.           (if (/= (char-after (car contain-stack)) ?{)
  1099.               (setq this-indent (car indent-stack))
  1100.                       ;; Line is at statement level.
  1101.                       ;; Is it a new statement?  Is it an else?
  1102.                       ;; Find last non-comment character before this line
  1103.                       (save-excursion
  1104.                         (setq this-point (point))
  1105.                         (setq at-else (looking-at "else\\W"))
  1106.                         (setq at-brace (= (following-char) ?{))
  1107.                         (setq at-while (looking-at "while\\b"))
  1108.                         (c-backward-to-noncomment opoint)
  1109.                         (if (not (memq (preceding-char) 
  1110.                                        '(nil ?\, ?\; ?} ?: ?{)))
  1111.                             ;; Preceding line did not end in comma or semi;
  1112.                             ;; indent this line  c-continued-statement-offset
  1113.                             ;; more than previous.
  1114.                             (progn
  1115.                               (c-backward-to-start-of-continued-exp
  1116.                                (car contain-stack))
  1117.                               (setq this-indent
  1118.                                     (+ c-continued-statement-offset
  1119.                                        (current-column)
  1120.                                        (if at-brace
  1121.                                            c-continued-brace-offset 
  1122.                                            0))))
  1123.                             ;; Preceding line ended in comma or semi;
  1124.                             ;; use the standard indent for this level.
  1125.                             (cond (at-else 
  1126.                                    (progn (c-backward-to-start-of-if opoint)
  1127.                                           (setq this-indent
  1128.                                                 (current-indentation))))
  1129.                                   ((and at-while 
  1130.                                         (c-backward-to-start-of-do opoint))
  1131.                                    (setq this-indent (current-indentation)))
  1132.                                   ((eq (preceding-char) ?\,)
  1133.                                    (goto-char this-point)
  1134.                                    (setq this-indent (calculate-c-indent)))
  1135.                                   (t 
  1136.                                    (setq this-indent (car indent-stack)))))))
  1137.                   ;; Just started a new nesting level.
  1138.                   ;; Compute the standard indent for this level.
  1139.                   (let ((val (calculate-c-indent
  1140.                               (if (car indent-stack)
  1141.                                   (- (car indent-stack))
  1142.                                   opoint))))
  1143.                     ;; t means we are in a block comment and should
  1144.                     ;; calculate accordingly.
  1145.                     (if (eq val t)
  1146.                         (setq val (calculate-c-indent-within-comment)))
  1147.                     (setcar indent-stack
  1148.               (setq this-indent val))))
  1149.           ;; Adjust line indentation according to its contents
  1150.           (if (or (looking-at c-switch-label-regexp)
  1151.               (and (looking-at "[A-Za-z]")
  1152.                (save-excursion
  1153.                  (forward-sexp 1)
  1154.                  (looking-at ":"))))
  1155.           (setq this-indent (max 1 (+ this-indent c-label-offset))))
  1156.           (if (= (following-char) ?})
  1157.           (setq this-indent (- this-indent c-indent-level)))
  1158.           (if (= (following-char) ?{)
  1159.                   ;; Don't move an open-brace in column 0.
  1160.                   ;; This is good when constructs such as
  1161.                   ;; `extern "C" {' surround a function definition
  1162.                   ;; that should be indented as usual.
  1163.                   ;; It is also good for nested functions.
  1164.                   ;; It is bad when an open-brace is indented at column 0
  1165.                   ;; and you want to fix that, but we can't win 'em all.
  1166.           (if (zerop (current-column))
  1167.                       (setq this-indent 0)
  1168.             (setq this-indent (+ this-indent c-brace-offset))))
  1169.           ;; Don't leave indentation in empty lines.
  1170.           (if (eolp) (setq this-indent 0))
  1171.           ;; Put chosen indentation into effect.
  1172.           (or (= (current-column) this-indent)
  1173.           (= (following-char) ?\#)
  1174.           (progn
  1175.             (delete-region (point)
  1176.                                    (progn (beginning-of-line) (point)))
  1177.             (indent-to this-indent)))
  1178.           ;; Indent any comment following the text.
  1179.           (or (looking-at comment-start-skip)
  1180.         (save-excursion
  1181.           (let ((beg (point)))
  1182.             (and (re-search-forward
  1183.               comment-start-skip
  1184.               (save-excursion (end-of-line) (point)) t)
  1185.              ;; Make sure the comment starter we found
  1186.              ;; is not actually in a string or quoted.
  1187.              (let ((new-state
  1188.                 (parse-partial-sexp beg (point)
  1189.                             nil nil state)))
  1190.                (and (not (nth 3 new-state))
  1191.                 (not (nth 5 new-state))))
  1192.              (indent-for-comment))))))))))))
  1193.  
  1194. ;;#### Unused -- commented out
  1195. ;; Look at all comment-start strings in the current line after point.
  1196. ;; Return t if one of them starts a real comment.
  1197. ;; This is not used yet, because indent-for-comment
  1198. ;; isn't smart enough to handle the cases this can find.
  1199. ;(defun indent-c-find-real-comment (state)
  1200. ;  (let ((win nil))
  1201. ;    (while (and (not win)
  1202. ;        (re-search-forward comment-start-skip
  1203. ;                   (save-excursion (end-of-line) (point))
  1204. ;                   t))
  1205. ;      ;; Make sure the comment start is not quoted.
  1206. ;      (let ((state-1
  1207. ;         (parse-partial-sexp
  1208. ;          (save-excursion (beginning-of-line) (point))
  1209. ;          (point) nil nil state)))
  1210. ;    (setq win (and (null (nth 3 state-1)) (null (nth 5 state-1))))))
  1211. ;    win))
  1212.  
  1213. ;; Indent every line whose first char is between START and END inclusive.
  1214. (defun c-indent-region (start end)
  1215.   (save-excursion
  1216.     (goto-char start)
  1217.     ;; Advance to first nonblank line.
  1218.     (skip-chars-forward " \t\n")
  1219.     (beginning-of-line)
  1220.     (let ((endmark (copy-marker end))
  1221.       (c-tab-always-indent t))
  1222.       (while (and (bolp) (not (eobp)) (< (point) endmark))
  1223.     ;; Indent one line as with TAB.
  1224.     (let ((shift-amt (c-indent-line))
  1225.           nextline sexpbeg sexpend)
  1226.       (if (save-excursion (beginning-of-line) (looking-at "[ \t]*#"))
  1227.           (forward-line 1)
  1228.         (save-excursion
  1229.           ;; Find beginning of following line.
  1230.           (save-excursion
  1231.         (forward-line 1) (setq nextline (point)))
  1232.           ;; Find first beginning-of-sexp for sexp extending past this line.
  1233.           (beginning-of-line)
  1234.           (while (< (point) nextline)
  1235.         (condition-case nil
  1236.             (progn
  1237.               (forward-sexp 1)
  1238.               (setq sexpend (point-marker)))
  1239.           (error (setq sexpend nil)
  1240.              (goto-char nextline)))
  1241.         (skip-chars-forward " \t\n"))
  1242.           (if sexpend
  1243.           (progn
  1244.             ;; Make sure the sexp we found really starts on the
  1245.             ;; current line and extends past it.
  1246.             (goto-char sexpend)
  1247.             (backward-sexp 1)
  1248.             (setq sexpbeg (point)))))
  1249.         ;; If that sexp ends within the region,
  1250.         ;; indent it all at once, fast.
  1251.         (if (and sexpend (> sexpend nextline) (<= sexpend endmark)
  1252.              (< sexpbeg nextline))
  1253.         (progn
  1254.           (indent-c-exp)
  1255.           (goto-char sexpend)))
  1256.         ;; Move to following line and try again.
  1257.         (and sexpend (set-marker sexpend nil))
  1258.         (forward-line 1))))
  1259.       (set-marker endmark nil))))
  1260.  
  1261. ;(defun set-c-style (style &optional global)
  1262. ;  "Set C-mode variables to use one of several different indentation styles.
  1263. ;The arguments are a string representing the desired style
  1264. ;and a flag which, if non-nil, means to set the style globally.
  1265. ;\(Interactively, the flag comes from the prefix argument.)
  1266. ;Available styles are GNU, K&R, BSD and Whitesmith."
  1267. ;  (interactive (list (completing-read "Use which C indentation style? "
  1268. ;                                    c-style-alist nil t)
  1269. ;                   current-prefix-arg))
  1270. ;  (let ((vars (cdr (assoc style c-style-alist))))
  1271. ;  (or vars
  1272. ;      (error "Invalid C indentation style `%s'" style))
  1273. ;  (while vars
  1274. ;    (or global
  1275. ;        (make-local-variable (car (car vars))))
  1276. ;    (set (car (car vars)) (cdr (car vars)))
  1277. ;    (setq vars (cdr vars)))))
  1278.  
  1279. ;;; This page handles insertion and removal of backslashes for C macros.
  1280.  
  1281. (defvar c-backslash-column 48
  1282.   "*Minimum column for end-of-line backslashes of macro definitions.")
  1283.  
  1284. (defun c-backslash-region (from to delete-flag)
  1285.   "Insert, align, or delete end-of-line backslashes on the lines in the region.
  1286. With no argument, inserts backslashes and aligns existing backslashes.
  1287. With an argument, deletes the backslashes.
  1288.  
  1289. This function does not modify the last line of the region if the region ends 
  1290. right at the start of the following line; it does not modify blank lines
  1291. at the start of the region.  So you can put the region around an entire macro
  1292. definition and conveniently use this command."
  1293.   (interactive "r\nP")
  1294.   (save-excursion
  1295.     (goto-char from)
  1296.     (let ((column c-backslash-column)
  1297.           (endmark (make-marker)))
  1298.       (move-marker endmark to)
  1299.       ;; Compute the smallest column number past the ends of all the lines.
  1300.       (if (not delete-flag)
  1301.           (while (< (point) to)
  1302.             (end-of-line)
  1303.             (if (= (preceding-char) ?\\)
  1304.                 (progn (forward-char -1)
  1305.                        (skip-chars-backward " \t")))
  1306.             (setq column (max column (1+ (current-column))))
  1307.             (forward-line 1)))
  1308.       ;; Adjust upward to a tab column, if that doesn't push past the margin.
  1309.       (if (> (% column tab-width) 0)
  1310.           (let ((adjusted (* (/ (+ column tab-width -1) tab-width) tab-width)))
  1311.             (if (< adjusted (window-width))
  1312.                 (setq column adjusted))))
  1313.       ;; Don't modify blank lines at start of region.
  1314.       (goto-char from)
  1315.       (while (and (< (point) endmark) (eolp))
  1316.         (forward-line 1))
  1317.       ;; Add or remove backslashes on all the lines.
  1318.       (while (and (< (point) endmark)
  1319.                   ;; Don't backslashify the last line
  1320.                   ;; if the region ends right at the start of the next line.
  1321.                   (save-excursion
  1322.                     (forward-line 1)
  1323.                     (< (point) endmark)))
  1324.         (if (not delete-flag)
  1325.             (c-append-backslash column)
  1326.           (c-delete-backslash))
  1327.         (forward-line 1))
  1328.       (move-marker endmark nil))))
  1329.  
  1330. (defun c-append-backslash (column)
  1331.   (end-of-line)
  1332.   ;; Note that "\\\\" is needed to get one backslash.
  1333.   (if (= (preceding-char) ?\\)
  1334.       (progn (forward-char -1)
  1335.              (delete-horizontal-space)
  1336.              (indent-to column))
  1337.     (indent-to column)
  1338.     (insert "\\")))
  1339.  
  1340. (defun c-delete-backslash ()
  1341.   (end-of-line)
  1342.   (forward-char -1)
  1343.   (if (looking-at "\\\\")
  1344.       (delete-region (1+ (point))
  1345.                      (progn (skip-chars-backward " \t") (point)))))
  1346.  
  1347. (defun c-up-conditional (count)
  1348.   "Move back to the containing preprocessor conditional, leaving mark behind.
  1349. A prefix argument acts as a repeat count.  With a negative argument,
  1350. move forward to the end of the containing preprocessor conditional.
  1351. When going backwards, `#elif' is treated like `#else' followed by `#if'.
  1352. When going forwards, `#elif' is ignored."
  1353.   (interactive "p")
  1354.   (c-forward-conditional (- count) t))
  1355.  
  1356. (defun c-backward-conditional (count &optional up-flag)
  1357.   "Move back across a preprocessor conditional, leaving mark behind.
  1358. A prefix argument acts as a repeat count.  With a negative argument,
  1359. move forward across a preprocessor conditional."
  1360.   (interactive "p")
  1361.   (c-forward-conditional (- count) up-flag))
  1362.  
  1363. (defun c-forward-conditional (count &optional up-flag)
  1364.   "Move forward across a preprocessor conditional, leaving mark behind.
  1365. A prefix argument acts as a repeat count.  With a negative argument,
  1366. move backward across a preprocessor conditional."
  1367.   (interactive "p")
  1368.   (let* ((forward (> count 0))
  1369.          (increment (if forward -1 1))
  1370.          (search-function (if forward 're-search-forward 're-search-backward))
  1371.          (opoint (point))
  1372.          (new))
  1373.     (save-excursion
  1374.       (while (/= count 0)
  1375.         (let ((depth (if up-flag 0 -1)) found)
  1376.           (save-excursion
  1377.             ;; Find the "next" significant line in the proper direction.
  1378.             (while (and (not found)
  1379.                         ;; Rather than searching for a # sign that comes
  1380.                         ;; at the beginning of a line aside from whitespace,
  1381.                         ;; search first for a string starting with # sign.
  1382.                         ;; Then verify what precedes it.
  1383.                         ;; This is faster on account of the fastmap feature of
  1384.                         ;; the regexp matcher.
  1385.                         (funcall search-function
  1386.                                  "#[ \t]*\\(if\\|elif\\|endif\\)"
  1387.                                  nil t))
  1388.               (beginning-of-line)
  1389.               ;; Now verify it is really a preproc line.
  1390.               (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\)")
  1391.                   (let ((prev depth))
  1392.                     ;; Update depth according to what we found.
  1393.                     (beginning-of-line)
  1394.                     (cond ((looking-at "[ \t]*#[ \t]*endif")
  1395.                            (setq depth (+ depth increment)))
  1396.                           ((looking-at "[ \t]*#[ \t]*elif")
  1397.                            (if (and forward (= depth 0))
  1398.                                (setq found (point))))
  1399.                           (t (setq depth (- depth increment))))
  1400.                     ;; If we are trying to move across, and we find
  1401.                     ;; an end before we find a beginning, get an error.
  1402.                     (if (and (< prev 0) (< depth prev))
  1403.                         (error (if forward
  1404.                                    "No following conditional at this level"
  1405.                                  "No previous conditional at this level")))
  1406.                     ;; When searching forward, start from next line
  1407.                     ;; so that we don't find the same line again.
  1408.                     (if forward (forward-line 1))
  1409.                     ;; If this line exits a level of conditional, exit inner loop.
  1410.                     (if (< depth 0)
  1411.                         (setq found (point)))))))
  1412.           (or found
  1413.               (error "No containing preprocessor conditional"))
  1414.           (goto-char (setq new found)))
  1415.         (setq count (+ count increment))))
  1416.     (push-mark)
  1417.     (goto-char new)))
  1418.  
  1419. ;;; c-mode.el ends here
  1420.